package com.android.djlmapp.activity.kaika;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.kaika.SelectTcAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.SxTimeDialog;
import com.android.djlmapp.listener.kaika.ShengXiaoTimeDialogListener;
import com.android.djlmapp.model.eventbus.SeleTcInfo;
import com.android.djlmapp.model.kaika.SelectTcInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.other.TextUtil;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SelectTaoCanActivity extends BaseActivity {

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.tc_phonenum)
    TextView tcPhonenum;
    @BindView(R.id.tc_address)
    TextView tcAddress;
    @BindView(R.id.listAccount)
    ExpandableListView listAccount;

    private ArrayList<SelectTcInfo.SpecList> selectTcData = new ArrayList<>();
    private SelectTcAdapter myAdapter;

    private String phoneNum = "";
    private String simNum = "";
    private String jiTuanNum = "";
    private String heYueId = "";
    private String addPara = "";
    private String yeWuType="";
    private String fkblNum="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_tc);
        ButterKnife.bind(this);
        initView();
        initData();

    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.VISIBLE);
        tvName.setText("选择套餐");
        // 业务类型
        yeWuType = getIntent().getStringExtra("YEWUTYPE");
        getKaiKaData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (listAccount != null) {
            listAccount.setEnabled(true);
        }

    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        switch (event.getCode()) {
            case EventCodes.EventKaiKaCode.C: // 实名认证完成
                finish();
                break;
        }
    }

    @Override
    protected void initData() {

        MyApplication.getInstance().getHttpTools().getSelectTcData(yeWuType, fkblNum,addPara, simNum, heYueId, jiTuanNum, phoneNum, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.e("项目异常specId", "------specId------" + response.body());
                try {
                    parseJson(response.body());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("项目异常getSelectTcData", "------数据解析异常------" + e.toString());
                    ToastUtils.showShortToast(SelectTaoCanActivity.this, "数据解析异常");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                ToastUtils.showShortToast(SelectTaoCanActivity.this, "网络或服务器错误");
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });

    }

    /**
     * 初始化加载列表
     */
    private void initExpendableListView() {

        myAdapter = new SelectTcAdapter(SelectTaoCanActivity.this);
        listAccount.setAdapter(myAdapter);
        myAdapter.setData(selectTcData);

        // 设置单选模式
        listAccount.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
        // ExpandableListView的子元素点击监听
        listAccount.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, final int childPosition, long id) {

                expendableListViewClick(groupPosition, childPosition);

                return false;
            }
        });
    }

    /**
     * 子条目点击事件
     * <p>
     * groupPosition
     * childPosition
     */
    private void expendableListViewClick(int groupPosition, int childPosition) {
        // 禁用点击事件，防止再次点击
        listAccount.setEnabled(false);
        SelectTcInfo.SpecList.Sys sysInfo = selectTcData.get(groupPosition).getSys().get(childPosition);
        String spec_id1 = sysInfo.getSpec_id1();
        String dp_price = sysInfo.getDp_price();
        String phone_price = sysInfo.getPhone_price();
        String price = sysInfo.getPrice();
        String spec_pric = sysInfo.getSpec_pric();
        String show_parms = sysInfo.getShow_parms();
        String spec_g_id = sysInfo.getSpec_g_id();
        String spec_name = sysInfo.getSpec_name();
        String spec_type = sysInfo.getSpec_type();
        String type_num = sysInfo.getType_num();


        ArrayList<SelectTcInfo.SpecList.Sys.Type> typeList = sysInfo.getType();

        if (typeList != null && typeList.size() > 0) {
            SxTimeDialog sxTimeDialog = new SxTimeDialog(SelectTaoCanActivity.this,
                    typeList, new ShengXiaoTimeDialogListener() {
                @Override
                public void TimeJump(int index) {

                    Event<String> selectNumEvent = new Event<>(EventCodes.EventKaiKaCode.A, "");
                    EventBusUtil.sendEvent(selectNumEvent);  // 通知选择号码界面关闭

                    String msg = typeList.get(index).getMsg();
                    String type_id = typeList.get(index).getType_id();

                    SeleTcInfo seleTcInfo = new SeleTcInfo();
                    seleTcInfo.setMsg(msg);
                    seleTcInfo.setType_id(type_id);
                    seleTcInfo.setPhoneNum(phoneNum);

                    seleTcInfo.setDp_price(dp_price);
                    seleTcInfo.setSpec_pric(spec_pric);
                    seleTcInfo.setPhone_price(phone_price);
                    seleTcInfo.setPrice(price);
                    seleTcInfo.setShow_parms(show_parms);
                    seleTcInfo.setSpec_g_id(spec_g_id);
                    seleTcInfo.setSpec_name(spec_name);
                    seleTcInfo.setSpec_type(spec_type);
                    seleTcInfo.setType_num(type_num);
                    seleTcInfo.setSpec_id1(spec_id1);

                    Event<SeleTcInfo> shiMingEvent = new Event<>(EventCodes.EventKaiKaCode.B, seleTcInfo);
                    EventBusUtil.sendEvent(shiMingEvent);


                    // 跳转界面
                    startActivity(new Intent(SelectTaoCanActivity.this, ShiMingRengZhengActivity.class)
                            .putExtra("CHENGKAJIHUO", 2).putExtra("SPECID", spec_id1)
                            .putExtra("selectPhoneNum", phoneNum));
                }

                @Override
                public void timeCancle() {
                    listAccount.setEnabled(true);
                }
            });

            sxTimeDialog.setCanceledOnTouchOutside(false);

            // dialog禁止返回键
            sxTimeDialog.setCancelable(false);
            sxTimeDialog.show();
        }
    }


    /**
     * 开卡/选号界面传递过来的数据
     */
    private void getKaiKaData() {
        phoneNum = getIntent().getStringExtra("phoneNum");
        String region = getIntent().getStringExtra("region");

        simNum = getIntent().getStringExtra("ICCIDNO");
        jiTuanNum = getIntent().getStringExtra("JTBM");
        heYueId = getIntent().getStringExtra("HEYUEID");
        addPara = getIntent().getStringExtra("ADDPARA");
        fkblNum = getIntent().getStringExtra("FKBL_NUM");

        if (TextUtils.isEmpty(simNum)) {
            simNum = "";
        }
        if (TextUtils.isEmpty(jiTuanNum)) {
            jiTuanNum = "";
        }
        if (TextUtils.isEmpty(heYueId)) {
            heYueId = "";
        }
        if (TextUtils.isEmpty(addPara)) {
            addPara = "";
        }

        String num = TextUtil.separateString(phoneNum, 3, 4, ' ');
        tcPhonenum.setText(num); // 分割号码
        tcAddress.setText(region);
        initExpendableListView();
    }

    /**
     * 解析套餐数据
     * <p>
     * json
     */
    private void parseJson(String json) {
        Gson gson = new Gson();
        SelectTcInfo selectTcInfo = gson.fromJson(json, SelectTcInfo.class);
        int code = selectTcInfo.getCode();
        if (code < 1000) {
            ArrayList<SelectTcInfo.SpecList> spec_list = selectTcInfo.getSpec_list();
            selectTcData.addAll(spec_list);
            myAdapter.setData(selectTcData);
            // 默认全部展开
            for (int i = 0; i < myAdapter.getGroupCount(); i++) {
                listAccount.expandGroup(i);
                myAdapter.notifyDataSetChanged();
            }
        } else {
            ToastUtils.showShortToast(SelectTaoCanActivity.this, selectTcInfo.getMsg());
        }

    }
}
